<template>
  <!-- TODO: Badge搜索框样式优化 -->
  <n-select
    ref="selectRef"
    clearable
    v-model:value="selectedValues"
    label-field="name"
    value-field="id"
    multiple
    filterable
    placeholder="添加标记"
    virtual-scroll
    :options="options"
    @update:value="selected"
    :renderTag="renderTag"
    @focus="wangwang"
  />
  <n-popover overlap trigger="click">
    <template #trigger><n-button> 设置</n-button></template>
    <n-button size="small" @click="createBadge">创建</n-button>
    <n-button size="small" @click="tosyncRemote">同步</n-button>
  </n-popover>

  <badge-edit-view ref="badgeEdit" :id="-1" />
  <n-modal
    v-model:show="showModal"
    preset="dialog"
    size="huge"
    :bordered="false"
    positive-text="确认"
    negative-text="算了"
    :closable="false"
    @positive-click="confirmCallback"
    @negative-click="cancelCallback"
    @after-leave="cancelCallback"
    @keydown.enter="confirmCallback"
  >
    <template #header>添加标记</template>
    <n-input-number v-model:value="inputvalue" clearable />
  </n-modal>
</template>

<script>
import { computed, h, ref } from "vue";
// import axios from "axios";
import { NInputNumber, NModal, NSelect, NTag, NPopover } from "naive-ui";
import BadgeEditView from "@/views/edit/BadgeEditView.vue";
import { useStore } from "vuex";

export default {
  components: {
    NSelect,
    NModal,
    NInputNumber,
    NPopover,
    BadgeEditView,
  },
  setup() {
    let selectedlength = ref(0); //  选择的长度，手动同步selectedValues
    let selectedValues = ref([]); //  被选择的数组
    let selectDict = ref({}); // 为被选中的东西记录额外属性

    let inputvalue = ref(0);

    const store = useStore();
    const badgeEdit = ref(null);
    const selectRef = ref(null);
    let showModal = ref(false);
    let options = computed(() => store.state.badge.list);
    /**
     * 打开创建标签
     */

    const createBadge = () => {
      badgeEdit.value.showModal = true;
    };

    /**
     * 请求远程同步标签
     */

    const tosyncRemote = () => {
      store.dispatch("getBadges", {
        success() {
          // console.log("同步成功");
        },
        error() {
          // message.error(`获取标签失败 {code:${error.response.status}}`);
        },
      });
    };

    /**
     * 输入框中标签的渲染函数
     */
    const renderTag = ({ option, handleClose }) => {
      // console.log(option);
      return h(
        NTag,
        {
          type: option.type,
          closable: true,
          onMousedown: (e) => {
            e.preventDefault();
          },
          onClose: (e) => {
            e.stopPropagation();
            handleClose();
          },
          size: "small",
        },
        { default: () => `${option.name} | ${selectDict[option.id].count}` }
      );
    };

    /***
     * 弹出框对新建标记进行数据完善(添加数值)
     * 通过对选择框绑定的 selectedValues 进行维护操作实现
     */

    const confirmCallback = (e) => {
      selectRef.value?.focus();
      if (e) e.stopPropagation();
      if (!showModal.value) return;
      selectedlength.value += 1;
      selectDict[selectedValues.value[selectedValues.value.length - 1]].count =
        inputvalue.value;

      showModal.value = false;
    };

    /**
     * 关闭数值确认框,维护同步
     *
     */
    const cancelCallback = () => {
      inputvalue.value = 0;
      while (selectedValues.value.length > selectedlength.value) {
        selectedValues.value.pop();
      }
    };

    let wangwang = () => {
      // console.log("wangwang");
    };

    /**
     * 监控变动，调用数据框
     * TODO: bug 一键清空按钮没有没正确相应
     */
    let selected = (values, selectedValues) => {
      if (selectedValues.length > selectedlength.value) {
        // 添加
        selectDict[values[values.length - 1]] = { count: 0 };
        showModal.value = true;
      } else {
        //   删除，跟进同步
        selectedlength.value = selectedValues.length;
      }
      // console.log(values);
    };
    return {
      wangwang,
      selectedValues,
      selected,
      selectedlength,
      showModal,
      renderTag,
      selectRef,
      inputvalue,
      confirmCallback,
      cancelCallback,
      selectDict,
      createBadge,
      badgeEdit,
      tosyncRemote,
      options,
      // 提取当前选取的标签
      getSelectArray: () => {
        let ret = [];
        for (let id of selectedValues.value) {
          ret.push({ badge: id, count: selectDict[id].count });
        }
        return ret;
      },
      // 赋值当前选取的标签
      setSelectArray: (badges) => {
        let ret = [];
        for (let tag of badges) {
          ret.push(tag.badge);
          selectDict[tag.badge] = { count: tag.count };
        }
        selectedValues.value = ret;
        selectedlength.value = ret.length;
        return ret;
      },
    };
  },
};
</script>

<style scoped>
.n-tag {
  cursor: pointer;
}
.n-tag:hover {
  box-shadow: 0 10px 10px -10px rgba(0, 0, 0, 0.5);
  /* -webkit-transform: scale(1.1);
  transform: scale(1.1); */
}
</style>